package com.jml.HashMap.ExtHashMap;

import java.util.Arrays;

public class ExtHashMap<K,V> implements ExtMap<K,V>{

	//定义table 存放HashMap数组元素,懒加载
	Node<K,V>[] table = null;

	int size;

	//负载因子	负载因子越小hash冲突几率越低
	float DEFAULT_LOAD_FACTOR = 0.75f;

	//table的默认初始大小是16
	int DEFAULT_INITIAL_CAPACITY = 1 << 4;


	@Override
	public V put(K key, V value) {
		if(table==null){
			table = new Node[DEFAULT_INITIAL_CAPACITY];
		}
		resize();
		int index = getIndex(key, table.length);
		Node<K, V> node = table[index];
		if(node==null){
			//没有发生hash冲突
			node = new Node<K,V>(key,value,null);
		}else{
			while(node!=null){
				//k是同一个，覆盖
				if(node.getKey().equals(key)||node.getKey()==key){
					return node.setValue(value);
				}else{
					node = node.getNext();
				}
			}
			//k不是同一个，新增
			//发生hash冲突,把这个节点放在第一个(冲突就放在第一个)
			Node oldNode=table[index];
			node = new Node<>(key,value,table[index]);
			node.setNext(oldNode);
		}
		table[index]=node;
		size++;
		return null;
	}

	public int getIndex(K k,int length){
		int hashCode = k.hashCode();
		//-1  +1  尽量减少越界的问题
		int index = hashCode % length;
		return index;
	}

	public void print(){
		System.out.println("-------------------------");
		for (int i = 0; i < table.length; i++) {
			Node<K, V> node = table[i];
			while(node!=null){
				int index = getIndex(node.getKey(), table.length);
				System.out.print("hashcode:"+index+"   下标位置"+"["+i+"]"+"  key:"+node.getKey()+"   value:"+node.getValue()+"          ");
				node=node.getNext();
			}
			System.out.println("");
		}
	}

	@Override
	public V get(K k) {
		Node<K, V> node = table[getIndex(k, table.length)];
		return getNode(node,k).getValue();
	}

	public Node<K, V> getNode(Node<K, V> node,K k){
		while(node!=null){
			if(node.getKey().equals(k)){
				return node;
			}
			node=node.getNext();
		}
		return null;
	}

	public void resize(){
//扩容
		if(size>(table.length*DEFAULT_LOAD_FACTOR)){
			//对table进行数组扩容
			Node<K,V>[] newTable = new Node[table.length<<1];
			for (int i = 0; i < table.length; i++) {
				Node<K, V> oldNode = table[i];
				while(oldNode!=null){
					int index = getIndex(oldNode.getKey(), newTable.length);
					Node<K, V> oldNext = oldNode.getNext();
					//newTable不是第一次赋值的时候
					if(newTable[index]!=null){
						Node<K, V> oldNextTemp = oldNode.getNext();
						oldNextTemp = newTable[index];
						newTable[index] = oldNode;
					}else{
						newTable[index] = oldNode;
					}
					oldNode = oldNext;
				}
			}
			table = null;//方便垃圾回收
			table = newTable;
			DEFAULT_INITIAL_CAPACITY = table.length;
		}
	}


	@Override
	public int size() {
		return 0;
	}
}
